package cn.kinoko.config.mybatis;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.sql.Statement;

/**
 * @author kk
 */
@Slf4j
@Component
@Intercepts({
        // 拦截query方法，指定方法重载的参数
        @Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class})
})
public class SqlUseTimeInterceptor implements Interceptor {

    @Value("${mybatis-plus.slow-sql:1000}")
    private int slowTime;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 获取开始时间
        long start = System.currentTimeMillis();
        // 获取执行的sql
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        String sql = statementHandler.getBoundSql().getSql();
        try {
            return invocation.proceed();
        } finally {
            long useTime = System.currentTimeMillis() - start;
            if (useTime >= slowTime) {
                log.warn("==> slow-sql catch !!! use {}ms {} sql=[{}] ", useTime, System.lineSeparator(), sql);
            } else {
                log.info("==> sql use {}ms", useTime);
            }
        }
    }

}
